/**
 *  判断传入的字符是否为大写
 * @param {*} character 要判断的字符
 * @returns  Boolean  传入的字符是否为大写
 */
function isUpperCase(character) {
  return /^[A-Z]$/.test(character);
}

function styleStr(value) {
  let str = "";
  for (const key in value) {
    str += `${stylechange(key)}:${value[key]};`;
  }
  return str;
}

function stylechange(str) {
  let result = "";
  let hasUppercase = false;

  for (let i = 0; i < str.length; i++) {
    let char = str.charAt(i);

    if (char === char.toUpperCase()) {
      hasUppercase = true;
      if (i > 0) {
        result += "-";
      }
      result += char.toLowerCase();
    } else {
      result += char;
    }
  }

  if (!hasUppercase) {
    return str;
  }
  return result;
}

// const jsx = (type, config) => {
//   /* TODO: 待补充代码 */
//   const dom = document.createElement(type);
//   for (const key in config) {
//     // console.log(config[key]);
//     // console.log(key);
//     const value = config[key];
//     if (key == "children") {
//       if (typeof value == "string") {
//         // console.log("str");
//         dom.appendChild(document.createTextNode(value));
//       } else {
//         // console.log("ob");
//         value.forEach((child) =>
//           typeof child === "string"
//             ? dom.appendChild(document.createTextNode(child))
//             : dom.appendChild(child)
//         );
//       }
//     } else if (key == "style") {
//       dom.setAttribute("style", styleStr(value));
//     } else if (typeof value == "function") {
//       // console.log("fun");
//       dom[key] = value;
//     } else {
//       dom.setAttribute(key, value);
//     }
//   }
//   return dom;
// };

const jsx = (type, config) => {
  /* TODO: 待补充代码 */
  let box = document.createElement(type);
  for (const key in config) {
    if (key == "children") {
      if (!/\[/g.test(JSON.stringify(config.children))) {
        box.innerHTML += config.children;
      } else {
        box.innerHTML += config.children[0] + config.children[1].outerHTML;
      }
    }
    if (key == "id") box.setAttribute("id", config.id);
    if (key == "style") {
      for (const key in config.style) {
        box.style[key] = config.style[key];
      }
    }
    if (key == "onclick") box.addEventListener("click", config.onclick);
  }
  return box;
};

const doConvert = async () => {
  try {
    const inputCode = document.getElementById("textarea").value;
    const res = eval(inputCode);
    const container = document.createElement("div");
    container.appendChild(res);
    if (res instanceof HTMLElement) {
      const html = await prettier.format(container.innerHTML, {
        parser: "html",
        plugins: prettierPlugins,
      });
      document.getElementById(
        "app-code"
      ).innerHTML = `<pre><code style="font-family: consolas; font-size: 14px;white-space: break-spaces;">${
        hljs.highlight(html, {
          language: "html",
          theme: "github-dark-dimmed",
        }).value
      }</code></pre>`;
      document.getElementById("app-view").innerHTML = "";
      document.getElementById("app-view").appendChild(res);
    } else {
      document.getElementById(
        "app-code"
      ).innerHTML = `<h3>jsx 转换出错，请检查代码</h3>`;
    }
  } catch (e) {
    document.getElementById(
      "app-code"
    ).innerHTML = `<h3>jsx 转换出错，请检查代码</h3>`;
    console.error("jsx 转换出错，请检查代码 >>> ", e);
  }
};

const target = [
  `
  jsx("div", {
    children: "hello"
  })
  `,
  `
  jsx("div", {
    children: [
    "hello",
    jsx("span", {
      children: "world"
    })
    ]
  })
  `,
  `
  jsx("div", {
    style: { color:'red', fontSize:'12px' }, // 样式
    id: 'id-1', // id
    children: "hello"
  })
  `,
  `
  jsx("div", {
    onclick: () => { // 点击触发的事件
      alert("div clicked!")
    },
    children: "hello"
  })
  `,
];

const restoreTargetByCustom = (str) => {
  document.getElementById("textarea").value = str;
  doConvert();
};

const restoreTarget = (targetNum) => {
  document.getElementById("textarea").value = target[targetNum];
  doConvert();
};

const changeToCode = () => {
  document.getElementById("code").checked = true;
  document.getElementById("view").checked = false;
  document.getElementById("app-code").style.display = "block";
  document.getElementById("app-view").style.display = "none";
};

const changeToView = () => {
  document.getElementById("code").checked = false;
  document.getElementById("view").checked = true;
  document.getElementById("app-code").style.display = "none";
  document.getElementById("app-view").style.display = "block";
};

window.onload = () => {
  restoreTarget(0);
};
